package j.quartz.controller;

import com.alibaba.fastjson.JSONObject;
import com.sun.tools.corba.se.idl.StringGen;
import j.quartz.zdao.entity.IUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Map;

/**
 * 系统Controller
 * 系统登录路由
 */
@Controller
public class JquartzController {
    private static final Logger LOGGER = LoggerFactory.getLogger(JquartzController.class) ;

    /**
     * 登录动作
     * @param view
     * @return
     */
    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request, ModelAndView view, IUser user ) {

        String method = request.getMethod();
        if("get".equalsIgnoreCase(method)) {
            Subject subject = SecurityUtils.getSubject();
            boolean authenticated = subject.isAuthenticated();
            if(authenticated) {
                LOGGER.info("已经认证过，直接跳转index");
                view.setViewName("redirect:/index");
                return view ;
            }
            LOGGER.info("没有验证过，进入登录页面");
            view.setViewName("sys/login");
            return view ;
        }

        JSONObject jsonObject = new JSONObject();

        String username = user.getUsername();
        String password = user.getPassword();
        LOGGER.info("获取到用户的登录信息：{} - {}",username,password);

        // 如果登录失败从request中获取认证异常信息，shiroLoginFailure就是shiro异常类的全限定名
        // 根据shiro返回的异常类路径判断，抛出指定异常信息
        String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
        if (exceptionClassName != null) {
            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
                view.addObject("errorMsg", "用户名不存在");
            } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
                view.addObject("errorMsg", "用户名/密码不正确");
            }else {

            }
        }
        // 此方法不处理登陆成功（认证成功），shiro认证成功会自动跳转到上一个请求路径
        // 登陆失败还到login页面

        /*Subject subject = SecurityUtils.getSubject();
        boolean authenticated = subject.isAuthenticated();
        if(authenticated) {
            LOGGER.info("已经认证过，直接跳转index");
            view.setViewName("redirect:/index");
            return view ;
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
            jsonObject.put("token", subject.getSession().getId());
            jsonObject.put("msg", "登录成功");
        } catch (IncorrectCredentialsException e) {
            jsonObject.put("msg", "密码错误");
        } catch (LockedAccountException e) {
            jsonObject.put("msg", "登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            jsonObject.put("msg", "该用户不存在");
        } catch (Exception e) {
            LOGGER.error("登录错误：",e);
        }
        view.addObject("errorMsg",jsonObject) ;*/
        LOGGER.info("错误了，转到登录页面！");
        view.setViewName("sys/login");
        return view ;
    }

    /**
     * 登录成功后 由 index 页面跳转到 /admin
     * @param view
     * @return
     */
//    @PermitAll
    @GetMapping("/admin")
    public ModelAndView admin (ModelAndView view) {
        LOGGER.info("进入 Admin 前 检查授权！");
        // 这时候会走 doGetAuthorizationInfo() 方法
        Subject subject = SecurityUtils.getSubject();
        subject.checkPermission("add1");
        subject.checkRole("admin");

        view.setViewName("sys/admin");
        return view ;
    }

    // 直接访问登录页
    @GetMapping("/index")
    public String index() {

        return "index" ;
    }


    //404
    @RequestMapping(value="/404")
    public String notFound(){
        return "sys/404";
    }

    @RequestMapping(value="/unauthorizedUrl")
    public String unauthorizedUrl(){
        return "sys/unauthorizedUrl";
    }

    /************************ 测试使用 ***************************/

    /**
     * 转到登录页面
     * @return
     */
    @GetMapping("/login.html")
    public String loginUrl() {

        return "sys/login" ;
    }




}
